﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net.Configuration;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Services;
using SAS.Bussiness;
using SAS.Core;
using SAS.Core.Entity;
using SAS.Core.Result;

namespace SAS.WebSite.Service
{
    public partial class Services
    {
        /*The services for users*/

        [WebMethod]
        public static string Users(string seid, object json, object search)
        {
            #region validate

            //validate inputted parameter
            if(string.IsNullOrEmpty(seid) || json == null)
                return string.Empty;

            #endregion

            //parse json data to objects
            AdvSearch advSearch = GetAdvanceSearch(json);
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string strsearch = serializer.Serialize(search);
            SearchParameters advsrch = serializer.Deserialize<SearchParameters>(strsearch);

            //call to business layer to get the data
            UserBO userBo = new UserBO
                {
                    FromIP = ClientIp
                };
            SASResult<IList<User>> bussinessResult = userBo.GetUsers(User, advSearch, advsrch);

            //serlialize object data to json
            var jsonObject = new
            {
                page = bussinessResult.OutputResult["PageNumber"],
                total = bussinessResult.OutputResult["PageSize"],
                records = bussinessResult.OutputResult["ResultCount"],
                rows = bussinessResult.Result,
                errorMessage = bussinessResult.Message
            };

            //return service call
            return serializer.Serialize(jsonObject);
        }

        [WebMethod]
        public static string AddUser(object json)
        {
            #region validate
            //validate json parameter
            if (String.IsNullOrEmpty(Convert.ToString(json)))
            {
                return string.Empty;
            }
            #endregion
            
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string strjson = serializer.Serialize(json);
            User newUser = serializer.Deserialize<User>(strjson);

            //get the physical web path.
            string webPhysicalPath = Path.GetDirectoryName(HttpContext.Current.Request.MapPath(""));

            //get new user email template path.
            string emailTemplatePath = ConfigurationManager.AppSettings.Get("NewUserEmailTemplate");

            //Build email template
            emailTemplatePath = String.Format(@"{0}\{1}", webPhysicalPath, emailTemplatePath);

            //Read web configuration.
            Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);

            //Read mail setting configuration.
            MailSettingsSectionGroup mailSettings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
            
            //get the SAS web access URL
            string sasAccessURL = ConfigurationManager.AppSettings.Get("SASAccessURL");

            //call to business layer to create data
            UserBO userBo = new UserBO
                {
                    FromIP = ClientIp
                };
            SASResult<int> bussinessResult = userBo.AddUser(User, newUser, mailSettings, emailTemplatePath, sasAccessURL);

            //serlialize object data to json
            var jsonObject = new
                                 {
                                     ReturnCode = bussinessResult.Result,
                                     errorMessage = bussinessResult.Message
                                 };

            //return service call
            return serializer.Serialize(jsonObject);
        }

        [WebMethod]
        public static string UserProfile()
        {
            UserBO userBO = new UserBO
                {
                    FromIP = ClientIp
                };
            SASResult<User> bussinessResult = userBO.GetUserCurrentUser(User);
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            //serlialize object data to json
            var jsonObject = new
                {
                    Email = bussinessResult.Result == null ? String.Empty : bussinessResult.Result.Email,
                    FirstName = bussinessResult.Result == null ? String.Empty : bussinessResult.Result.FirstName,
                    LastName = bussinessResult.Result == null ? String.Empty : bussinessResult.Result.LastName,
                    ClientRoleName = bussinessResult.Result == null ? String.Empty : bussinessResult.Result.ClientRoleName,
                    Title = bussinessResult.Result == null ? String.Empty : bussinessResult.Result.Title,
                    Phone1 = bussinessResult.Result == null ? String.Empty : bussinessResult.Result.Phone1,
                    Phone2 = bussinessResult.Result == null ? String.Empty : bussinessResult.Result.Phone2,
                    Address1 = bussinessResult.Result == null ? String.Empty : bussinessResult.Result.Address1,
                    Address2 = bussinessResult.Result == null ? String.Empty : bussinessResult.Result.Address2,
                    City = bussinessResult.Result == null ? String.Empty : bussinessResult.Result.City,
                    PostalCode = bussinessResult.Result == null ? String.Empty : bussinessResult.Result.PostalCode,
                    StateProv = bussinessResult.Result == null ? String.Empty : bussinessResult.Result.StateProv,
                    Country = bussinessResult.Result == null ? String.Empty : bussinessResult.Result.Country,
                    errorMessage = bussinessResult.Message
                };

            //return service call
            string strSerializedString = serializer.Serialize(jsonObject);
            return strSerializedString;
        }

        [WebMethod]
        public static string UpdateUserProfile(object json)
        {

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string strjson = serializer.Serialize(json);
            User userInfo = serializer.Deserialize<User>(strjson);

            UserBO userBO = new UserBO
                {
                    FromIP = ClientIp
                };

            userBO.UpdateUser(User, userInfo);
            return String.Empty;
        }

        [WebMethod]
        public static string UpdateUser(object json)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string strjson = serializer.Serialize(json);
            User userInfo = serializer.Deserialize<User>(strjson);

            //call to business layer to create data
            UserBO userBo = new UserBO
            {
                FromIP = ClientIp
            };

            userBo.UpdateUser(User, userInfo);

            return "";
        }

        [WebMethod]
        public static string UserRoles()
        {
            //call to business layer to get the data
            UserBO userBo = new UserBO
                {
                    FromIP = ClientIp
                };
            SASResult<IList<string>> userRoles = userBo.GetRoleNames(User);
            var jsonObject = new
            {
                dropDownItem = userRoles.Result,
                errorMessage = userRoles.Message
            };

            //serialize and return json message
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(jsonObject);
        }

        [WebMethod]
        public static string ResetPassword(string email, string origination)
        {
            //Read web configuration.
            Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);

            //Read mail setting configuration.
            MailSettingsSectionGroup settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");

            //get the physical web path.
            string webPhysicalPath = Path.GetDirectoryName(HttpContext.Current.Request.MapPath(""));

            //get active email template path.
            string emailTemplatePath = ConfigurationManager.AppSettings.Get("ForcedUserEmailTemplate");

            //locate activate email template.
            string templatePath = String.Format(@"{0}\{1}", webPhysicalPath, emailTemplatePath);

            //get the SAS web access URL
            string sasAccessURL = ConfigurationManager.AppSettings.Get("SASAccessURL");

            UserBO userBo = new UserBO
                {
                    FromIP = ClientIp
                };

            SASResult<bool> resetResult = userBo.ResetPassword(User, email, origination, settings, templatePath, sasAccessURL);
            var jsonObject = new
            {
                errorMessage = resetResult.Message
               
            };
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(jsonObject);
        }

        [WebMethod]
        public static string LogOut()
        {
            UserBO userBo = new UserBO
            {
                FromIP = ClientIp
            };

            SASResult<bool> logOutResult = userBo.LogOut(User);

            if(logOutResult.IsSucessful && logOutResult.Result)
            {
                //destroy user session
            }

            var jsonObject = new
            {
                logOutResult = logOutResult.Result,
                errorMessage = logOutResult.Message
            };

            //serialize and return json message
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(jsonObject);
        }

        [WebMethod]
        public static string ChangePassword(string fh, string np, string secret)
        {
            UserBO userBo = new UserBO
            {
                FromIP = ClientIp
            };

            //userBo.Ch
            return string.Empty;
        }
    }
}